<template>
  <el-dialog
    title="查看实时报文"
    width="800"
    v-model="dialogVisible"
    :show-close="false"
    :modal="true"
    :close-on-click-modal="false"
  >
    <!-- 添加文本框区域 -->
    <el-input
      type="textarea"
      :rows="20"
      v-model="formattedMessages"
      readonly
      placeholder="正在等待获取报文..."
      class="message-display"
      ref="messageTextarea"
    ></el-input>

    <template #footer>
      <el-row class="custom-row">
        <el-form-item class="custom-form-item">
          <el-button type="primary" @click="clearMessages">清空</el-button>
        </el-form-item>
        <el-form-item class="custom-form-item">
          <el-button @click="closeDialog">确定</el-button>
        </el-form-item>
      </el-row>
    </template>
  </el-dialog>
</template>

<script setup name="AddConnection" lang="ts">
import {ref, computed, watch, type ComponentPublicInstance} from "vue";
import {nextTick} from "vue";
import {getLatestMessage} from "@/api/deviceApi.ts";

let props = defineProps({
  deviceName: {
    type: String,
    required: true,
  },
});
const dialogVisible = ref(false);
// 响应式数据
const messages = ref<string[]>([]) // 存储原始报文数据
const messageTextarea = ref<ComponentPublicInstance | null>(null); // 明确类型
const isLoading = ref(false)
const poller = ref() // 轮询实例

// 格式化报文为每行一条的文本
const formattedMessages = computed(() => {
  return messages.value.join('\n')
})

// 获取报文数据的API调用
const fetchMessages = async () => {
  try {
    isLoading.value = true
    const data = await getLatestMessage(props.deviceName) // 替换为您的实际API
    if (Array.isArray(data) && data.length > 0) {
      messages.value.push(...data);
    }
  } catch (error) {
    console.error('获取报文失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 打开对话框
const openDialog = () => {
  dialogVisible.value = true
  startPolling() // 开始轮询
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  stopPolling() // 停止轮询
}

const clearMessages = () => {
  messages.value = []
}

// 开始轮询
const startPolling = () => {
  poller.value = setInterval(fetchMessages, 1000) // 1秒轮询一次
  fetchMessages() // 立即执行一次
}

// 停止轮询
const stopPolling = () => {
  if (poller.value) {
    // 清除定时器
    clearInterval(poller.value)
  }
}
// 如果需要从父组件控制对话框显示
defineExpose({
  openDialog,
  closeDialog
});

// 监听 formattedMessages 的变化
watch(formattedMessages, () => {
  nextTick(() => {
    // 确保 DOM 更新后执行滚动操作
    if (messageTextarea.value) {
      const textareaEl = messageTextarea.value.$el.querySelector('textarea');
      textareaEl.scrollTop = textareaEl.scrollHeight; // 滚动到底部
    }
  });
});
</script>

<style scoped>
.config-container {
  width: 400px;
  padding: 20px;
  text-align: left;
}

/* 自定义滚动条 */
.message-display .el-textarea__inner::-webkit-scrollbar {
  width: 6px;
  background: #f5f5f5;
}

.message-display .el-textarea__inner::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

/* Firefox 兼容 */
.message-display .el-textarea__inner {
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f5f5f5;
}

.el-form-item {
  margin-bottom: 15px;
}

.custom-row {
  display: flex;
  justify-content: center;
  /* 居中对齐 */
  align-items: center;
  /* 垂直居中（如果需要的话） */
}

.custom-form-item {
  margin: 0 10px;
  /* 左右的间距，根据需要调整 */
}

/* 如果你不想给第一个和最后一个元素添加边距，可以使用伪类选择器 */
.custom-row .custom-form-item:first-child {
  margin-left: 0;
}

.custom-row .custom-form-item:last-child {
  margin-right: 0;
}
</style>
